#include "stdafx.h"
#include "FBO.h"

FBO::FBO()
{
    glGenFramebuffers(1, &fboHandle);
}

void FBO::bind() { glBindFramebuffer(GL_FRAMEBUFFER, fboHandle); }
void FBO::unbind() { glBindFramebuffer(GL_FRAMEBUFFER, 0); }

//-----------------------------------------------//

FBO_RB::FBO_RB(glm::dvec2 dim, GLenum colorFormat)
{
    // creation 
    glGenRenderbuffers(1, &rbColorHandle);
    glGenRenderbuffers(1, &rbDepthHandle);
    // init rb storage 
    glBindRenderbuffer(GL_RENDERBUFFER, rbColorHandle);
    glRenderbufferStorage(GL_RENDERBUFFER, colorFormat, static_cast<GLsizei>(dim.x), static_cast<GLsizei>(dim.y));
    glBindRenderbuffer(GL_RENDERBUFFER, rbDepthHandle);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, static_cast<GLsizei>(dim.x), static_cast<GLsizei>(dim.y));

    // attach rb's to fbo 
    bind();
    glBindRenderbuffer(GL_RENDERBUFFER, rbColorHandle);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbColorHandle);
    glBindRenderbuffer(GL_RENDERBUFFER, rbDepthHandle);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbDepthHandle);

    ::checkFramebuffer(GL_FRAMEBUFFER, "Terrain::initPickingFBO()");
    unbind();
    ::flushGLError("FBO()");
}

glm::vec4 FBO_RB::sample(glm::dvec2 pos)
{
    glm::vec4 pixel;
    bind();
    glReadPixels( static_cast<GLint>(pos.x), static_cast<GLint>(pos.y), 1, 1, GL_RGBA, GL_FLOAT, &pixel.x);
    unbind();

    ::flushGLError("FBO_RB::sample()");
    return pixel;
}

//-----------------------------------------------//

FBO_Tex::FBO_Tex()
{
    
}

void FBO_Tex::attach(Texture texture, GLenum attPoint)
{
    bind();
    glFramebufferTexture(GL_FRAMEBUFFER, attPoint, texture.get(), 0);
    unbind();
}

glm::vec4 FBO_Tex::sample(glm::dvec2 pos)
{
    glm::vec4 pixel[4];
    bind();
    glReadPixels( static_cast<GLint>(pos.x), static_cast<GLint>(pos.y), 1, 1, GL_RGBA, GL_FLOAT, &pixel);
    unbind();

    ::flushGLError("FBO_Tex::sample()");
    return pixel[0];
}